<template>
	<el-checkbox-group v-model="check" :disabled="disabled" v-bind="$attrs">
		<el-checkbox v-for="item in items" :key="item" :label="getLabel(item)" :value="getValue(item)">{{
				getLabel(item)
		}}
		</el-checkbox>
	</el-checkbox-group>
</template>

<script setup>
import { ref, watch, computed, onBeforeMount } from "vue";
import Server from './Server.js'

const props = defineProps({
	modelValue: String,
	options: [Array, String],
	url: String,
	disabled: {
		type: Boolean,
		default: false,
	},
	valueField: {
		type: String,
		default: "value"
	},
	labelField: {
		type: String,
		default: "label"
	},
});

const serverOptions = ref([]);

onBeforeMount(async()=>{
	if(props.url && serverOptions.value.length==0){
		serverOptions.value = await Server.cache_call(props.url);
	}
})


const items = computed(() => {
	if (props.url) {
		return serverOptions.value;
	}
	if (Array.isArray(props.options)) {
		return props.options;
	}
	return (props.options || "").split(";").filter(p => p.trim().length > 0);
})

const emit = defineEmits(["update:modelValue"]);

const check = ref([]);

check.value = (props.modelValue || "").split(";").filter(p => p.trim().length > 0);

watch(check, (newVal) => {
	let vv = (newVal || []).join(";");
	if (vv != props.modelValue) {
		emit("update:modelValue", vv);
	}
});

watch(() => props.modelValue, (newValue) => {
	check.value = (newValue || "").split(";").filter(p => p.trim().length > 0);
})


const getLabel = function (tag) {
	if (Array.isArray(props.options)) {
		return tag[props.labelField];
	}
	if(props.url){
		return tag[props.labelField];
	}
	return tag;
}

const getValue = function (tag) {
	if (Array.isArray(props.options)) {
		return tag[props.valueField];
	}
	if(props.url){
		return tag[props.valueField];
	}
	return tag;
}



</script>
